package java0.conc0303;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本周作业：（必做）思考有多少种方式，在main函数启动一个新线程或线程池，
 * 异步运行一个方法，拿到这个方法的返回值后，退出主线程？
 * 写出你的方法，越多越好，提交到github。
 * <p>
 * 一个简单的代码参考：
 */
public class Homework03ReentrantLock {

    // 使用 ReentrantLock + Condition
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition c1 = lock.newCondition();




    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();

        SumThread sumThread = new SumThread();
        sumThread.start();

        lock.lock();
        try {
            c1.await();
        } finally {
            lock.unlock();
        }
        Integer result = sumThread.getResult();
        System.out.println("ReentrantLock + Condition方法异步计算结果为：" + result);

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        // 然后退出main线程
    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }

    static class SumThread extends Thread {
        private Integer result;

        public Integer getResult() {
            return result;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                result = sum();
                c1.signalAll();
            } finally {
                lock.unlock();
            }

        }
    }
}
